package com.hutao.example.wardemo.listener;

import com.hutao.example.wardemo.util.XmlUtil;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class AListener implements ServletContextListener {

    private ScheduledExecutorService scheduler;
    private String channel;

    @Override
    public void contextInitialized(ServletContextEvent sce) {

        channel = XmlUtil.readNode("com/hutao/example/wardemo/config/test.xml", "author");
        System.out.println("channel:" + channel);

        if (channel.equals("cwms")) {
            // 初始化定时器：创建一个单线程的定时任务线程池
            scheduler = Executors.newSingleThreadScheduledExecutor();

            // 提交定时任务：延迟0秒后开始，每5秒执行一次
            scheduler.scheduleAtFixedRate(
                    new Runnable() {
                        @Override
                        public void run() {
                            System.out.println("定时中····");
                        }
                    },  // 任务实例
                    0,                // 初始延迟时间
                    5,           // 间隔时间
                    TimeUnit.SECONDS  // 时间单位（秒）
            );
            System.out.println("定时器已启动...");
        }


    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        if (scheduler != null && !scheduler.isShutdown()) {
            scheduler.shutdown();
            System.out.println("定时器已关闭...");
        }
    }
}
